package com.ly.common.core.utils;

import cn.hutool.core.util.StrUtil;
import com.ly.common.core.constant.BaseConstant;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类
 *
 * @author luoyun
 */
public class DateUtils {
    /**
     * 根据周期类型返回当前周期
     *
     * @方法名称: getPeriodByPeriodType
     * @参数: @param periodtype
     * @参数: @return
     * @返回: String
     * @创建者: luowd
     * @创建时间: 2016年3月16日 下午2:25:00
     */
    public static String getPeriodByPeriodType(String periodtype) {
        String result = null;
        if ("1".equals(periodtype)) {
            result = getCurYear() + "";
        } else if ("2".equals(periodtype)) {
            result = getYearHY();
        } else if ("3".equals(periodtype)) {
            result = getYearQ();
        } else {
            result = getYearMonth();
        }
        return result;
    }

    /**
     * 返回当前年月
     *
     * @return
     */
    public static String getYearMonth(String date) {
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        try {
            result = sdf.format(convertStrToDate(date, "yyyy-MM-dd"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            ;
        }
        return result;
    }

    public static Date convertStrToDate(String str, String format) {
        Date date = new Date();
        try {
            if (str != null && format != null) {
                if (format.length() >= 10 && format.length() > str.length()) {
                    format = format.substring(0, str.length());
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            date = sdf.parse(str);
        } catch (ParseException e) {
            ;
        }
        return date;
    }

    /**
     * 返回当前年月
     *
     * @return
     */
    public static String getYearMonthXS(String date) {
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        try {
            result = sdf.format(convertStrToDate(date, "yyyyMM"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            ;
        }
        return result;
    }

    /**
     * 返回当前年月
     *
     * @return
     */
    public static String getYearMonth() {
        String result = null;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        result = sdf.format(date);
        return result;
    }

    /**
     * 返回当前年月日
     *
     * @return
     */
    public static String getYearMonthDay() {
        String result = null;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        result = sdf.format(date);
        return result;
    }

    /**
     * 将yyyyMMdd转化为date，计算传入的时间到当前时间相差天数
     *
     * @return
     */
    public static long convertYearMonthDayToDate(String yearMonthDay) {
        Date result = null;
        LocalDate localDate = LocalDate.now();
        LocalDate localDateNow = LocalDate.now();
        Period period = Period.between(localDate, localDateNow);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            result = sdf.parse(yearMonthDay);
            localDate = dateToLocalDate(result);
            period = Period.between(localDate, localDateNow);
        } catch (Exception e) {
            ;
        }
        return period.getDays();
    }

    public static LocalDate dateToLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * 返回当前年月
     *
     * @return
     */
    public static String getDateString(Date date, String format) {
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        result = sdf.format(date);
        return result;
    }

    /**
     * 根据考核周期获取周期类型
     *
     * @方法名称: getPeriodTypeByCode
     * @职责说明:
     * @参数: @param periodCode
     * @参数: @return
     * @返回: String
     * @创建者: Lilc
     * @创建时间: 2013-4-28 下午04:09:55
     */
    public static String getPeriodTypeByCode(String periodCode) {
        if (StrUtil.isNotEmpty(periodCode)) {
            int length = periodCode.length();
            if (length == 4) {
                return BaseConstant.PERIODTYPE_Y;
            } else if (length == 6) {
                String t = periodCode.substring(4, 5);
                if ("Y".equalsIgnoreCase(t)) {
                    // 半年
                    return BaseConstant.PERIODTYPE_HY;
                } else if ("Q".equalsIgnoreCase(t)) {
                    // 季度
                    return BaseConstant.PERIODTYPE_Q;
                } else {
                    // 月
                    return BaseConstant.PERIODTYPE_M;
                }
            }
        }
        return null;
    }

    /**
     * 传入某年某月值得到月末最后一天的日期
     *
     * @方法名称: getLastdayOfMonth
     * @职责说明: 获取某年某月最后一天
     * @参数: @param year
     * @参数: @param month
     * @参数: @return
     * @返回: int
     * @创建者: daru.zheng
     * @创建时间: 2013-4-11 上午09:30:07
     */
    public static int getLastdayOfMonth(int year, int month) {
        int result = 31;
        if (month == 4 || month == 6 || month == 9 || month == 11) {
            result = 30;
        } else if (month == 2) {
            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                result = 29;
            } else {
                result = 28;
            }
        }
        return result;
    }

    /**
     * 得到当前季度
     *
     * @方法名称: getYearQ
     * @参数: @return
     * @返回: String
     * @创建者: luowd
     * @创建时间: 2014年11月12日 上午9:49:02
     */
    public static String getYearQ() {
        String yearq = getCurYear() + "";
        Calendar now = Calendar.getInstance();
        int month = now.get(Calendar.MONTH) + 1;
        if (month == 1 || month == 2 || month == 3) {
            yearq = yearq + "Q1";
        } else if (month == 4 || month == 5 || month == 6) {
            yearq = yearq + "Q2";
        } else if (month == 7 || month == 8 || month == 9) {
            yearq = yearq + "Q3";
        } else if (month == 10 || month == 11 || month == 12) {
            yearq = yearq + "Q4";
        }
        return yearq;
    }

    /**
     * @方法名称: getYearHY
     * @参数: @return
     * @返回: String
     * @创建者: luowd
     * @创建时间: 2014年11月17日 下午5:00:22
     */
    public static String getYearHY() {
        String yeary = getCurYear() + "";
        Calendar now = Calendar.getInstance();
        int month = now.get(Calendar.MONTH) + 1;
        if (month <= 6) {
            yeary = yeary + "Y1";
        } else {
            yeary = yeary + "Y2";
        }
        return yeary;
    }

    /**
     * 返回当前年（四位）
     *
     * @return int
     */
    public static int getCurYear() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.YEAR);
    }

    /**
     * @核心介绍: 根据当前周期获得上期代码
     * @类名: com.nci.epm.utils.DateUtil
     * @方法名: getLastPeriodByThisPeriod
     * @参数: @param periodCode
     * @参数: @return
     * @创建人: xufei
     * @创建时间:　2015-1-7 下午02:13:06
     */
    public static String getLastPeriodByThisPeriod(String periodCode) {
        String periodFeq = getPeriodTypeByCode(periodCode);
        String lastYear = (Integer.parseInt(periodCode.substring(0, 4)) - 1) + "";
        String thisYear = periodCode.substring(0, 4);
        String lastPeriod = "";
        if (periodFeq.equals(BaseConstant.PERIODTYPE_Y)) {
            lastPeriod = lastYear;
        } else if (periodFeq.equals(BaseConstant.PERIODTYPE_M)) {
            int month = Integer.parseInt(periodCode.substring(4));
            if (month == 1) {
                lastPeriod = lastYear + "12";
            } else {
                String monthStr = "0" + (month - 1);
                lastPeriod = thisYear + monthStr.substring(monthStr.length() - 2);
            }
        } else if (periodFeq.equals(BaseConstant.PERIODTYPE_Q)) {
            int thisQ = Integer.parseInt(periodCode.substring(5));
            if (thisQ == 1) {
                lastPeriod = lastYear + "Q4";
            } else {
                lastPeriod = thisYear + "Q" + (thisQ - 1);
            }
        } else {
            int thisHY = Integer.parseInt(periodCode.substring(5));
            if (thisHY == 1) {
                lastPeriod = lastYear + "Y2";
            } else {
                lastPeriod = thisYear + "Y1";
            }
        }
        return lastPeriod;
    }

    public static String convertDateToString(Date date, String format) {
        if (date == null) {
            return "";
        }
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        result = sdf.format(date);
        return result;
    }

    /**
     * 获取xx月之前或之后的日期
     *
     * @param month
     * @return
     * @author caoxiaobo 2019年9月11日 下午4:49:15
     */
    public static String getDate(int month) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, month);// 对月份进行计算,减去12个月
        Date date = cal.getTime();
        return df.format(date);
    }

    /**
     * 获取xx月之前或之后的日期
     *
     * @param month
     * @return
     * @author caoxiaobo 2019年9月11日 下午4:49:15
     */
    public static String getDate(int month, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, month);// 对月份进行计算,减去12个月
        Date date = cal.getTime();
        return df.format(date);
    }

    /**
     * 获取最近几个月的日期
     *
     * @param length
     * @return
     * @author caoxiaobo 2019年9月11日 下午6:45:42
     */
    public static String[] getLatestYearMonth(int length) {
        String[] months = new String[length];
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); // 要先+1,才能把本月的算进去
        for (int i = length - 1; i >= 0; i--) {
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); // 逐次往前推1个月						
            int x = cal.get(Calendar.MONTH) + 1;
            String m = (x < 10) ? "0" + x : String.valueOf(x);
            months[length - 1 - i] = cal.get(Calendar.YEAR) + "年" + m + "月";
        }
        return months;
    }

    public static String[] getLatestYearMonthKing(int length) {
        String[] months = new String[length];
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); // 要先+1,才能把本月的算进去
        for (int i = length - 1; i >= 0; i--) {
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); // 逐次往前推1个月						
            int x = cal.get(Calendar.MONTH) + 1;
            String m = (x < 10) ? "0" + x : String.valueOf(x);
            months[length - 1 - i] = cal.get(Calendar.YEAR) + m;
        }
        return months;
    }

    /**
     * 获取最近几个月的日期
     *
     * @param length
     * @return YYYY-MM-
     * @author caoxiaobo 2019年9月11日 下午6:45:42
     */
    public static String[] getLatestYearMonth(int length, String format) {
        format = format.toUpperCase();
        String y = format.substring("YYYY".length(), format.indexOf("MM"));
        String m = format.substring(format.indexOf("MM") + 2);
        String[] months = new String[length];
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); // 要先+1,才能把本月的算进去
        for (int i = length - 1; i >= 0; i--) {
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); // 逐次往前推1个月						
            int x = cal.get(Calendar.MONTH) + 1;
            String month = (x < 10) ? "0" + x : String.valueOf(x);
            months[length - 1 - i] = cal.get(Calendar.YEAR) + y + month + m;
        }
        return months;
    }

    /**
     * 获取最近几个月的日期
     *
     * @param start
     * @param format
     * @param length
     * @return YYYY-MM-
     * @author caoxiaobo 2019年11月27日 下午4:25:24
     */
    public static String[] getLatestYearMonth(String start, int length, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            format = format.toUpperCase();
            String y = format.substring("YYYY".length(), format.indexOf("MM"));
            String m = format.substring(format.indexOf("MM") + 2);
            String[] months = new String[length];
            Calendar cal = Calendar.getInstance();
            Date beginDate = sdf.parse(start);
            cal.setTime(beginDate);
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); // 要先+1,才能把本月的算进去
            for (int i = length - 1; i >= 0; i--) {
                cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); // 逐次往前推1个月						
                int x = cal.get(Calendar.MONTH) + 1;
                String month = (x < 10) ? "0" + x : String.valueOf(x);
                months[length - 1 - i] = cal.get(Calendar.YEAR) + y + month + m;
            }
            return months;
        } catch (Exception e) {
            ;
        }
        return null;
    }

    /**
     * 功能说明：获取当前系统时间
     *
     * @return
     * @author Peied 2011-10-9 下午04:54:33
     */
    public static String getCurrentDateTime() {
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date nowDate = new Date();
        result = sdf.format(nowDate);
        return result;
    }

    /**
     * @param @return 参数yyyyMM是要显示的年月样式
     * @return String 返回类型
     * @throws
     * @Title: getLastMonth
     * @Description: TODO(返回上个月yyyyMM格式字符串)
     * @author butid
     */
    public static String getLastMonth(String yyyyMM) {
        SimpleDateFormat format = new SimpleDateFormat(yyyyMM);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
        String lastMonthStr = format.format(calendar.getTime());
        return lastMonthStr;
    }

    public static String getDesignatedMonth(String yyyyMM, int designated) {
        SimpleDateFormat format = new SimpleDateFormat(yyyyMM);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + designated); // 设置为指定的月
        String lastMonthStr = format.format(calendar.getTime());
        return lastMonthStr;
    }

    /**
     * @param @param  yyyyMMdd 返回的日期的字符串的样式
     * @param @param  designated
     * @param @param  Calendar_Type 加减参数的类型，如月Calendar.MONTH
     * @param @return 参数
     * @return String 返回类型
     * @throws
     * @Title: getDesignatedDate
     * @Description: TODO(以当前日期为几种 ， 通过加减designated个指定数量的Calendar_Type来获取指定日期)
     */
    public static String getDesignatedDate(String yyyyMMdd, int designated, int Calendar_Type) {
        SimpleDateFormat format = new SimpleDateFormat(yyyyMMdd);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar_Type, calendar.get(Calendar_Type) + designated);
        String rtnStr = format.format(calendar.getTime());
        return rtnStr;
    }

    /**
     * 返回当前年月
     *
     * @return
     */
    public static String getYearMonth(Date date) {
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        try {
            result = sdf.format(date);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            ;
        }
        return result;
    }

    /**
     * 获取两段日期的小时
     *
     * @param sDate
     * @param eDate
     * @return
     * @throws ParseException
     */
    public static double gethuor(String sDate, String eDate) throws ParseException {
        DateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date startDate = simpleFormat.parse(sDate);
        Date endDate = simpleFormat.parse(eDate);
        long startTime = startDate.getTime();
        long endTime = endDate.getTime();
        double huor = (double) ((endTime - startTime) / (1000 * 60 * 60));
        return huor;
    }

    /**
     * 字符串转日期格式
     */
    public static Date date(String date_str) {
        try {
            Calendar zcal = Calendar.getInstance();
            Timestamp timestampnow = new Timestamp(zcal.getTimeInMillis());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ParsePosition pos = new ParsePosition(0);
            java.util.Date current = formatter.parse(date_str, pos);
            timestampnow = new Timestamp(current.getTime());
            return timestampnow;
        } catch (NullPointerException e) {
            return null;
        }
    }

    /**
     * 获取当前日期信息，根据传入的格式输出
     *
     * @param pattern
     * @return
     */
    public static String getNowTimeByPattern(String pattern) {
        LocalDateTime now = LocalDateTime.now();
        if (pattern == null) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return now.format(formatter);
    }
}
